package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("setmeal")
public class SetmealController {

    @Autowired
    SetmealService setmealService;

    @PostMapping
    //在调用保存方法之后,需要删除key值为categoryId结尾的缓存
    @CacheEvict(cacheNames = "setmeal_", key = "#setmealDto.categoryId")
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveAndDish(setmealDto);
        return R.success("添加套餐成功");
    }



    @GetMapping("page")
    public R<Page<SetmealDto>> page(Integer page, Integer pageSize, String name) {
        Page<SetmealDto> pageInfo = setmealService.page(page, pageSize, name);
        return R.success(pageInfo);
    }

    @DeleteMapping
    @CacheEvict(cacheNames = "setmeal_", allEntries = true)
    public R<String> delete(Long[] ids) {

        setmealService.deleteAndDish(ids);
        return R.success(null);
    }

   /* @PostMapping("/status/{num}")
    public R<String> ceshi(@PathVariable Integer num,Long ids) {
        System.out.println("hhhh");
        System.out.println(num);
        System.out.println(ids);
        return R.success(null);
    }*/

    @GetMapping("list")
    @Cacheable(cacheNames = "setmeal_", key = "#setmeal.categoryId+','+setmeal.status", unless = "#result == null")

    public R<List<Setmeal>> list(Setmeal setmeal) {

        LambdaQueryWrapper<Setmeal> queryWrapper = Wrappers.lambdaQuery(Setmeal.class)
                .eq(Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(Setmeal::getStatus, setmeal.getStatus())
                .orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

}
